/**
 * simple class that sends push notifications.
 */

package com.bowlofnoodles.truffles;

import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.io.IOException;
import java.io.OutputStreamWriter;

import javax.servlet.http.HttpServletResponse;

public class TrufflePusher {
	
	private URL url;
	private HttpURLConnection conn;
	
	String authToken;
	StringBuilder sb;
	
	public TrufflePusher(String aT) {
		try {
			authToken = aT;
			url = new URL("https://android.apis.google.com/c2dm/send");
			conn = (HttpURLConnection) url.openConnection();
			conn.setDoOutput(true);
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
			//conn.setRequestProperty("Authorization", "GoogleLogin auth="+authToken);
			// auth cookie from the test account
			conn.setRequestProperty("Authorization", "GoogleLogin auth="+"DQAAAKIAAAAFS6vrJAOQpnDJfQjMs_GyVo28Mcqu4E86lRbSYbFfGJLO9mhjIthzI_dI9sQVCFFqSKH5Sqo0SEZL5tT4eW8sHTw0-it3xvg1omP_O9A7_lqoklO6aNYkCQLOfXXQxi7fzZu7qxPAGom9AFegmaQgTNf7iI_mY8JLAnDBBHdEs6csQaH0MH-qRmsE9sM0cJKQioY4J38kUw6yaTSN52sOk4iJd1tz7zedsmHJ210Y_A");
			sb = new StringBuilder();
			
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void push(String reg_id, String gramsFound, HttpServletResponse resp) throws IOException {
		
		// assemble the query
		sb.append("registration_id=");
		sb.append(reg_id);
		sb.append("&collapse_key=0");
		sb.append("&gramsFound=");
		sb.append(gramsFound);
		
		conn.setFixedLengthStreamingMode(sb.length());
		conn.setRequestProperty("Content-Length", sb.length()+"");
		
		resp.getWriter().println("reg_id: "+reg_id);
		
		try {
			OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
			writer.write(sb.toString());
			writer.flush();
			writer.close();
			
			resp.getWriter().println(conn.getResponseCode());
			resp.getWriter().println(conn.getResponseMessage());
			int b = -1;
			do {
				b = conn.getInputStream().read();
				if (b!=-1)resp.getWriter().print((char)b);
			} while (b != -1);
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}
